<template>
  <div class="search-container">
      <!-- search 事件在手机键盘上的完成或者搜索(PC端回车) -->
      <!-- cancel 事件在点击取消文字的时候触发 -->
       <!-- 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮。 -->
    <form action="/" class="search-box">
      <van-search
        v-model="serachText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        background="#3296fa"
        shape="round"
        @clear='isResultShow=false'
      />
    </form>

    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :search-text="serachText" />
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion 
    :serach-text="serachText" 
    v-else-if="serachText" 
    @search='onSearch'
    />
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history 
    v-else 
    :search-histories='searchHistories'
     @search='onSearch'/>
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import SearchResult from "./components/search-result";
import SearchHistory from "./components/search-history";
import SearchSuggestion from "./components/search-suggestion";
import { setItem,getItem} from '@/utiles/storage'
export default {
  name: "Search",
  components: {
    SearchResult,
    SearchHistory,
    SearchSuggestion,
  },
  data() {
    return {
      serachText: "", //输入文字
      isResultShow: false, // 搜索结果是否显示
      searchHistories:getItem('TOUTIAO_HISTORY') || [] //搜索历史
    };
  },
  watch: {
    searchHistories:{
      deep:true,
      handler() {
       setItem('TOUTIAO_HISTORY',this.searchHistories)
      }
    },
    serachText(){
      if (!this.serachText) this.isResultShow=false
    }
    
  },
  methods: {
    onSearch(val) {
      console.log(val);
      // 通过子父通信 传递搜索建议的值赋值到输入框中
      this.serachText=val
      // 去重
      let idx=this.searchHistories.findIndex(item=>item===val)
      if(idx !==-1) this.searchHistories.splice(idx,1)
      // 把值放入历史
      this.searchHistories.unshift(val)
      this.isResultShow=true
    },
    onCancel() {
      console.log("hh");
      this.$router.back()
    },
  },
};
</script>

<style lang="less" scoped>
.van-search__action {
  color: #fff;
}
.search-box {
  position: sticky; //粘性定位
  top: 0;
  z-index: 1000;
}
</style>
